package com.web.hawaste.controller;

import com.web.hawaste.entity.SysUser;
import com.web.hawaste.utils.ResponseStatus;
import com.web.hawaste.utils.ResultBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * YangSuzy 软件工作室
 * 类名: MainController
 * 描述: ---- 待定 -----
 * 功能: ---- 待定 -----
 *
 * @author YangSuzy
 * Date: 2022/10/14 16:56
 */
@Controller
public class MainController {
    /**
     * 方法名: doLogin
     * 描述: 登录请求逻辑实现
     *
     * @param params
     * @param session
     * @return com.web.hawaste.utils.ResultBean
     * @date 2022/10/14 17:19
     * @auther YangSuzy
     **/
    @PostMapping("/doLogin")
    @ResponseBody
    public ResultBean doLogin(
            @RequestBody Map<String, Object> params,
            HttpSession session) {
        String username = (String) params.get("username");
        String password = (String) params.get("password");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        if (subject.isAuthenticated()) {
            SysUser user = (SysUser) subject.getPrincipal();
            session.setAttribute("loginUser", user);
            HashMap<String, Object> map = new HashMap<>();
            map.put("loginUser", user);
            return ResultBean.ok(map);
        }
        return ResultBean.fail(ResponseStatus.USERNAME_PASS_ERROR);
    }

    @GetMapping("/logout")
    public String loginOut() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login.html";
    }
}
